package com.hefan.robot.service;

import com.hefan.common.ons.TopicRegistry;
import com.hefan.common.ons.bean.Message;
import com.hefan.common.ons.service.ONSProducer;
import com.hefan.common.util.MapUtils;
import com.hefan.live.itf.LiveImOptService;
import com.hefan.live.itf.LivingRedisOptService;
import com.hefan.robot.common.util.RandomUtil;
import com.hefan.robot.configCenter.RobotConfigCenter;
import com.hefan.robot.itf.RandLightRoom;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.Map;

/**
 * Created by nigle on 2016/12/12.
 */
@Path("/robot")
@Component("randLightRoom")
public class RandLightRoomImpl implements RandLightRoom{
    public Logger logger = LoggerFactory.getLogger(RobotInitServiceImpl.class);

    @Resource
    LivingRedisOptService livingRedisOptService;
    @Resource
    LiveImOptService liveImOptService;
    @Resource
    ONSProducer onsProducer;
    @Resource
    private RobotConfigCenter robotConfigCenter;

    @GET
    @Path("/randLight")
    @Consumes({ MediaType.APPLICATION_JSON })
    @Produces({ MediaType.APPLICATION_JSON })
    @Override
    public void randLight() {
        //全部直播信息
        Map<String,String> mapAll = livingRedisOptService.getAllLivingInfo_Hash();
        if ( null != mapAll && mapAll.isEmpty()){
            logger.info("没有正在进行的直播，随机点亮直播间任务发布结束");
            return;
        }
        logger.info("随机点亮直播间任务发布开始");
        //机器人首次点亮的延时时间，单位毫秒
        Map<String,String> propty = robotConfigCenter.getPublicConfig();
        long delayTimeMin = MapUtils.getLongValue(propty,"robot.rand.light.delay.time.min",0);
        long delayTimeMax = MapUtils.getLongValue(propty,"robot.rand.light.delay.time.max",0);
        String onsEnv = MapUtils.getStrValue(propty, "ons.env", "");
        for (Map.Entry<String, String> entry : mapAll.entrySet()) {
            int i = 0;//计数器
            long delayTime = RandomUtil.getRandom(delayTimeMin, delayTimeMax);
            //没观众则首次延时多加10秒
            if(livingRedisOptService.getLivingUserCount_SortedSet(entry.getKey())<=0){ delayTime += 10000; }
            //发送本直播间十分钟内N条随机点亮消息，delayTimeMin到delayTimeMax内随机一条，根据配置文件定
            while ( delayTime < 1000*60*10){
                Message message = new Message();
                message.put("vo", entry.getValue());
                message.setTopic(TopicRegistry.HEFAN_ROBOT_ACTION_RAND_LIGHT_DELAY);
                message.setTag(onsEnv);
                onsProducer.sendDelayMsg(message, delayTime);
                delayTime += RandomUtil.getRandom(delayTimeMin, delayTimeMax);
                i++;
            }
            logger.info("{}的直播间十分钟内发送了{}条点亮消息", entry.getKey(), i);
        }
        logger.info("随机点亮直播间任务发布结束");
    }
}
